package com.league.blog.utils;

import org.apache.shiro.codec.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @author 黄豪琦
 * 日期:2019-05-23 18:09
 * 说明:字符串工具类
 */
public class StringUtils {


    public static boolean isBlank(String str){
        boolean result = false;
        if(str == null || str.length() <= 0 || "".equals(str.trim())){
            result = true;
        }
        return result;
    }

    /**
     * 从头开始截取index位
     * @param index
     * @param target
     * @return
     */
    public static String headSplit(int index, String target){
        return target.substring(0, index);
    }


    public static String getRandomStr(int length){
        String result = UUID.randomUUID().toString().replace("-", "");
        return result.substring(0, length);
    }
    
    public static String getRandomStr(){
        return UUID.randomUUID().toString().replace("-", "");
    }

    /**
     * 获取被toString后的User对象的accountName;
     * @param target
     * @return
     */
    public static String splitUserName(String target) {
        if (target == null) {
            throw new NullPointerException("切割的目标为null");
        }
        int a, b;
        a = target.indexOf("accountName");
        b = target.indexOf("'", a);
        return target.substring(b + 1, target.indexOf("'", b + 1));
    }

    private void generateSecretKey(){
        try {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecretKey deskey = keygen.generateKey();
            System.out.println(Base64.encodeToString(deskey.getEncoded()));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将2020-04-08 10:29:53格式的日期字符串转换为2020/04/08格式的
     * @param target
     * @return
     */
    public static String formatDate(String target){
        return  target!=null?target.substring(0, target.indexOf(" ")).replaceAll("-", "/"):null;
    }
}
